<template>
	<view :style="themeColor()">
		<view class="bg-[var(--page-bg-color)] min-h-screen overflow-hidden" v-if="!loading">
			<view v-if="!loading" class="pb-20rpx">
				<view class="pl-[40rpx] pr-[50rpx] bg-linear pb-[100rpx]">
					<!-- #ifdef MP-WEIXIN -->
					<top-tabbar :data="topTabbarData" :scrollBool="topTabarObj.getScrollBool()" />
					<!-- #endif -->
					<view class="flex justify-between items-center pt-[40rpx]">
						<view class="text-[#fff] text-[36rpx] font-500 leading-[42rpx]">{{ formatOrderStatus(detail) }}</view>
						<image v-if="detail.status == 0" class="w-[180rpx] h-[140rpx]" :src="img('addon/shop/detail/payment.png')"
							mode="aspectFit" />
						<image v-if="detail.status == 10" class="w-[180rpx] h-[140rpx]"
							:src="img('addon/shop/detail/deliver_goods.png')" mode="aspectFit" />
						<image v-if="detail.status == 20" class="w-[180rpx] h-[140rpx]" :src="img('addon/shop/detail/receive.png')"
							mode="aspectFit" />
						<image v-if="detail.status == 30" class="w-[180rpx] h-[140rpx]" :src="img('addon/shop/detail/complete.png')"
							mode="aspectFit" />
						<image v-if="detail.status == 40" class="w-[180rpx] h-[140rpx]" :src="img('addon/shop/detail/close.png')"
							mode="aspectFit" />
					</view>
				</view>
				<view class="sidebar-margin mt-[-86rpx] card-template">
					<view v-if="detail.deliveryType == 1">
						<view class="text-[#303133] flex">
							<text class="nc-iconfont nc-icon-dizhiguanliV6xx text-[40rpx] pt-[12rpx] mr-[20rpx]"></text>
							<view class="flex flex-col">
								<view class="text-[30rpx] leading-[38rpx] overflow-hidden">
									<text>{{ detail.receiverName }}</text>
									<text class="ml-[15rpx]">{{ detail.receiverMobile }}</text>
								</view>
								<view class="mt-[12rpx] text-[24rpx] text-[var(--text-color-light6)] leading-[26rpx]">
									{{ detail.receiverAreaName }}{{ detail.receiverDetailAddress }}
								</view>
							</view>

						</view>
					</view>
					<view v-if="detail.deliveryType == 2">
						<view class="flex items-center">
							<view>
								<u--image class="overflow-hidden" radius="var(--goods-rounded-mid)" width="100rpx" height="100rpx"
									:src="img(detail.store.logo ? detail.store.logo : '')" model="aspectFill">
									<template #error>
										<image class="w-[100rpx] h-[100rpx] rounded-[var(--goods-rounded-mid)] overflow-hidden"
											:src="img('addon/shop/store_default.png')" mode="aspectFill"></image>
									</template>
								</u--image>
							</view>
							<view class="flex flex-col ml-[20rpx]">
								<text class="text-[30rpx] font-500 text-[#303133] mb-[20rpx]">{{ detail.store.name }}</text>
								<!-- <text class="text-[24rpx] text-[var(--text-color-light6)] mb-[14rpx]">{{ detail.store.trade_time
								}}</text> -->
								<!-- <text class="text-[24rpx] text-[var(--text-color-light6)] mb-[14rpx]">{{ detail.store.areaName
								}}</text> -->
								<text class="text-[24rpx] text-[var(--text-color-light6)] leading-[1.4]">{{ detail.store.detailAddress
								}}</text>
							</view>
						</view>
					</view>
					<view class="flex" v-if="detail.delivery_type == 'local_delivery'">
						<text @click="getAddress"
							class="nc-iconfont nc-icon-dizhiguanliV6xx text-[40rpx] pt-[12rpx] mr-[20rpx]"></text>
						<view class="flex flex-col">
							<view class="flex leading-[38rpx] overflow-hidden">
								<text class="text-[30rpx]">{{ detail.taker_name }}</text>
								<text class="text-[30rpx] ml-[15rpx]">{{ detail.taker_mobile }}</text>
							</view>
							<text class="text-[24rpx] mt-[12rpx] leading-[26rpx]">{{ detail.taker_full_address }}</text>
						</view>
					</view>
				</view>
				<view class="sidebar-margin card-template p-[0] py-[var(--pad-top-m)] overflow-hidden"
					:class="{ 'pb-[var(--pad-top-m)]': detail.gift_goods.length <= 0 }"
					:style="detail.delivery_type == 'virtual' ? 'margin-top: -86rpx' : 'margin-top: 20rpx'">
					<view v-for="(goodsItem, goodsIndex) in detail.goods" :key="goodsIndex" class="px-[var(--pad-sidebar-m)]">
						<view class="order-goods-item flex justify-between flex-wrap mb-[20rpx]">
							<view class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
								@click="goodsEvent(goodsItem.spuId)">
								<u--image class="overflow-hidden" radius="var(--goods-rounded-big)" width="150rpx" height="150rpx"
									:src="img(goodsItem.picUrl ? goodsItem.picUrl : '')" model="aspectFill">
									<template #error>
										<image class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
											:src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill">
										</image>
									</template>
								</u--image>
							</view>

							<view class="ml-[20rpx] flex flex-1 flex-col justify-between">
								<view>
									<view class="text-[32rpx] max-w-[490rpx] truncate leading-[40rpx] text-[#333]">{{ goodsItem.titleName
										||
										goodsItem.spuName
									}}
									</view>

								</view>
								<view>

									<view v-if="goodsItem.properties">
										<view class="text-[28rpx] text-[var(--text-color-light9)] truncate max-w-[490rpx] leading-[28rpx]">
											{{ skuSpecFormat(goodsItem.properties) }}
										</view>
									</view>
								</view>
								<view class="flex justify-between items-baseline leading-[28rpx] text-[#333]">
									<view class="price-font">
										<view class="text-[40rpx] inline-block" v-if="goodsItem.point && parseFloat(goodsItem.point) > 0">
											<text class="text-[40rpx] font-200">{{ goodsItem.point }}</text>
											<text class="text-[32rpx] ml-[4rpx]">积分</text>
										</view>
										<text class="mx-[4rpx] text-[32rpx]"
											v-if="parseFloat(goodsItem.price) && goodsItem.point && parseFloat(goodsItem.point) > 0">+</text>
										<block v-if="parseFloat(goodsItem.price) && goodsItem.point && parseFloat(goodsItem.point) > 0">
											<text class="text-[40rpx] font-200">{{ parseFloat(fen2yuan(goodsItem.price)).toFixed(2) }}</text>
											<text class="text-[32rpx] ml-[4rpx]">元</text>
										</block>
										<block v-if="goodsItem.extend && goodsItem.extend && goodsItem.extend.is_newcomer">
											<text class="text-[24rpx]">￥</text>
											<text class="text-[40rpx] font-500">{{ parseFloat(goodsItem.price).toFixed(2).split('.')[0]
											}}</text>
											<text class="text-[24rpx] font-500">.{{ parseFloat(goodsItem.price).toFixed(2).split('.')[1]
											}}</text>
										</block>
										<block v-if="parseFloat(goodsItem.price) && !goodsItem.extend">
											<text class="text-[24rpx]">￥</text>
											<text class="text-[40rpx] font-500">{{
												parseFloat(diyGoods.fen2yuan(goodsItem.price)).toFixed(2).split('.')[0]
											}}</text>
											<text class="text-[24rpx] font-500">.{{
												parseFloat(diyGoods.fen2yuan(goodsItem.price)).toFixed(2).split('.')[1]
											}}</text>
										</block>
									</view>
									<text class="text-right text-[28rpx]">x{{ goodsItem.count }}</text>
								</view>
							</view>
						</view>
						<view class="flex items-center box-border mt-[8rpx]"
							v-if="goodsItem.extend && goodsItem.extend.is_newcomer && goodsItem.num > 1">
							<image class="h-[24rpx] w-[56rpx]" :src="img('addon/shop/newcomer.png')" mode="heightFix" />
							<view class="text-[24rpx] text-[#FFB000] leading-[34rpx] ml-[8rpx]">
								第1{{ goodsItem.unit }}，￥{{ parseFloat(goodsItem.extend.newcomer_price).toFixed(2) }}/{{ goodsItem.unit
								}}；第{{
									goodsItem.num > 2 ? '2~' + goodsItem.num : '2' }}{{ goodsItem.unit }}，￥{{
									parseFloat(goodsItem.price).toFixed(2)
								}}/{{ goodsItem.unit }}
							</view>
						</view>
						<view class="flex justify-end w-[100%] mt-[30rpx]"
							v-if="(goodsItem.status != 0) || (goodsItem.afterSaleStatus == 20)">
							<view v-if="goodsItem.afterSaleStatus == 20 || goodsItem.afterSaleStatus == 10"
								class="text-[28rpx] text-[#303133] leading-[50rpx] px-[20rpx] border-[2rpx] border-solid border-[#999] rounded-full"
								@click="redirect({ url: '/addon/shop/pages/refund/detail', param: { order_refund_no: goodsItem.afterSaleId } })">
								查看退款</view>

							<view v-else-if="[10, 20, 30, 80].includes(detail.status) && goodsItem.afterSaleStatus == 0"
								class="text-[28rpx] text-[#303133]  leading-[50rpx] px-[20rpx] border-[2rpx] border-solid border-[#999] rounded-full ml-[20rpx]"
								@click="applyRefund(goodsItem.id)">申请退款</view>
						</view>
					</view>
					<view class="pt-[20rpx] bg-[#f9f9f9] mt-[20rpx] mx-[var(--pad-sidebar-m)] rounded-[var(--rounded-big)]"
						v-if="detail.gift_goods.length">
						<view class="order-goods-item flex justify-between flex-wrap px-[var(--pad-sidebar-m)] pb-[20rpx]"
							v-for="(goodsItem, goodsIndex) in detail.gift_goods" :key="goodsIndex">
							<view class="w-[120rpx] h-[120rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
								@click="goodsEvent(goodsItem.goods_id)">
								<u--image class="overflow-hidden" radius="var(--goods-rounded-big)" width="120rpx" height="120rpx"
									:src="img(goodsItem.goods_image_thumb_small ? goodsItem.goods_image_thumb_small : '')"
									model="aspectFill">
									<template #error>
										<image class="w-[120rpx] h-[120rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
											:src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill">
										</image>
									</template>
								</u--image>
							</view>
							<view class="ml-[16rpx] py-[8rpx] flex flex-1 flex-col justify-between">
								<view class="flex items-center">
									<view
										class="bg-[var(--primary-color-light)] whitespace-nowrap text-[var(--primary-color)] rounded-[6rpx] text-[28rpx] flex items-center justify-center w-[64rpx] h-[34rpx] mr-[6rpx]">
										赠品</view>
									<view class="text-[28rpx] max-w-[400rpx] truncate leading-[40rpx] text-[#333]">{{ goodsItem.goods_name
									}}
									</view>
								</view>
								<view class="flex items-center">
									<view v-if="goodsItem.sku_name"
										class="text-[28rpx] text-[var(--text-color-light9)] truncate max-w-[400rpx] leading-[28rpx]">
										{{ goodsItem.sku_name }}
									</view>
									<view class="ml-[auto] font-400 text-[28rpx] text-[#303133]">
										<text>x</text>
										<text>{{ goodsItem.num }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="sidebar-margin mt-[var(--top-m)] card-template">
					<view class="justify-between card-template-item">
						<view class="text-[32rpx]">{{ t('orderNo') }}</view>
						<view class="flex items-center text-[32rpx]">
							<text>{{ detail.no }}</text>
							<text class="w-[2rpx] h-[20rpx] bg-[#999] mx-[10rpx]"></text>
							<text class="text-[#EF900A]" @click="copy(detail.no)">复制</text>
						</view>
					</view>
					<!-- <view v-if="detail.out_trade_no" class="justify-between card-template-item">
						<view class="text-[32rpx]">{{ t('orderTradeNo') }}</view>
						<view class="text-[32rpx]">{{ detail.out_trade_no }}</view>
					</view> -->
					<view class="justify-between card-template-item">
						<view class="text-[32rpx]">订单类型 </view>
						<view class="text-[32rpx]">{{ formatOrderType(detail) }}</view>
					</view>
					<view class="justify-between card-template-item">
						<view class="text-[32rpx]">{{ t('createTime') }}</view>
						<view class="text-[32rpx]">{{ timeFormat(detail.createTime, 'yyyy-mm-dd hh:MM:ss') }}</view>
					</view>
					<view class=" card-template-item justify-between">
						<view class="text-[32rpx]">{{ t('deliveryType') }}</view>
						<view class="text-[32rpx]">{{ detail.deliveryType == 1 ? '物流配送' : '门店自提' }}</view>
					</view>
					<view v-if="detail.payChannelName" class=" card-template-item justify-between">
						<view class="text-[32rpx]">{{ t('payTypeName') }}</view>
						<view class="text-[32rpx]">{{ detail.payChannelName || '-' }}</view>
					</view>
					<view v-if="detail.payTime" class=" card-template-item justify-between">
						<view class="text-[32rpx]">{{ t('payTime') }}</view>
						<view class="text-[32rpx]">{{ timeFormat(detail.payTime, 'yyyy-mm-dd hh:MM:ss') }}</view>
					</view>
				</view>
				<!-- 核销码 -->
				<block v-if="isShowVerify">
					<view class="sidebar-margin  mt-[var(--top-m)] card-template">
						<!-- <swiper class="h-[450rpx]" circular indicator-dots="true" v-if="verifyInfo.length > 1">
							<swiper-item v-for="(item, index) in verifyInfo" :key="index">
								<view class="flex flex-col items-center justify-center">
									<image :src="painterImageUrl" class="w-[300rpx] h-[auto]" mode="widthFix"></image>
								</view>
								<view class="flex items-center justify-center mt-[30rpx]">
									<text class="text-[32rpx] font-500">{{ item.code }}</text>
									<text
										class="text-[var(--text-color-light6)] text-[24rpx] ml-[10rpx] border-[2rpx] border-solid border-[#666] bg-[#f7f7f7] px-[12rpx] py-[6rpx] rounded"
										@click="copy(item.code)">复制</text>
								</view>
							</swiper-item>
						</swiper> -->
						<!-- <block v-else> -->
						<view class="flex flex-col items-center justify-center">
							<!-- <image :src="detail.pickUpVerifyCode" class="w-[300rpx] h-[auto]" mode="widthFix"></image> -->
							<image v-if="!!painterImageUrl" :src="painterImageUrl" class="w-[300rpx] h-[auto]" mode="widthFix">
							</image>

						</view>
						<view class="flex items-center justify-center mt-[30rpx]">
							<text class="text-[32rpx] font-500">{{ detail.pickUpVerifyCode }}</text>
							<text
								class="text-[var(--text-color-light6)] text-[24rpx] ml-[10rpx] border-[2rpx] border-solid border-[#666] bg-[#f7f7f7] px-[12rpx] py-[6rpx] rounded"
								@click="copy(detail.pickUpVerifyCode)">复制</text>
						</view>
						<!-- </block> -->

					</view>
					<!-- <view class="sidebar-margin mt-[var(--top-m)] card-template">
						<view class="title">核销信息</view>
						<view class="card-template-item justify-between">
							<view class="text-[32rpx]">核销次数</view>
							<view class="price-font font-500 text-[32rpx]">
								{{ '剩余' + (verifyGoodsData.num - verifyGoodsData.verify_count) + '次' }}/{{ '共' + verifyGoodsData.num +
									'次' }}
							</view>
						</view>
						<view class="card-template-item justify-between">
							<view class="text-[32rpx]">有效期</view>
							<view class="price-font font-500 text-[32rpx]">
								{{ verifyGoodsData.verify_expire_time ? verifyGoodsData.verify_expire_time : '永久' }}
							</view>
						</view>
					</view> -->
				</block>
				<view class="sidebar-margin mt-[var(--top-m)] card-template">
					<view class="card-template-item justify-between">
						<view class="text-[32rpx]">{{ t('goodsMoney') }}</view>
						<view class="price-font font-500">
							<text v-if="parseFloat(detail.point) > 0" class="text-[32rpx]">{{ detail.point }}积分</text>
							<text v-if="parseFloat(detail.point) > 0 && parseFloat(detail.goods_money)"
								class="mx-[4rpx] text-[32rpx]">+</text>
							<block v-if="parseFloat(detail.totalPrice) || !parseFloat(detail.point)">
								<text class="text-[32rpx]">￥</text>
								<text class="text-[32rpx]">{{ parseFloat(diyGoods.fen2yuan(detail.totalPrice)).toFixed(2).split('.')[0]
								}}</text>
								<text class="text-[32rpx]">.{{ parseFloat(diyGoods.fen2yuan(detail.totalPrice)).toFixed(2).split('.')[1]
								}}</text>
							</block>
						</view>
					</view>
					<view class=" card-template-item justify-between" v-if="parseFloat(detail.deliveryPrice)">
						<view class="text-[32rpx]">{{ t('deliveryMoney') }}</view>
						<view class="price-font font-500 text-[32rpx]">
							￥{{ parseFloat(diyGoods.fen2yuan(detail.deliveryPrice)).toFixed(2) }}
						</view>
					</view>
					<!-- <view class=" card-template-item justify-between">
						<view class="text-[32rpx]">{{ t('discountMoney') }}</view>
						<view class="price-font font-500 text-[32rpx]">
							-￥{{ parseFloat(detail.discount_money).toFixed(2) }}
						</view>
					</view> -->
					<view class=" card-template-item justify-between" v-if="parseFloat(detail.couponPrice)">
						<view class="text-[32rpx]">优惠券优惠</view>
						<view class="price-font font-500 text-[32rpx]">
							￥{{ parseFloat(diyGoods.fen2yuan(detail.couponPrice)).toFixed(2) }}
						</view>
					</view>
					<!-- <view class=" card-template-item justify-between" v-if="parseFloat(detail.manjian_discount_money)">
						<view class="text-[32rpx]">满减优惠</view>
						<view class="price-font font-500 text-[32rpx]">
							-￥{{ parseFloat(detail.manjian_discount_money).toFixed(2) }}
						</view>
					</view> -->
					<view class=" card-template-item justify-between" v-if="parseFloat(detail.pointPrice)">
						<view class="text-[32rpx]">积分抵扣</view>
						<view class="price-font font-500 text-[32rpx]">
							￥{{ parseFloat(diyGoods.fen2yuan(detail.pointPrice)).toFixed(2) }}
						</view>
					</view>
					<view class=" card-template-item justify-between" v-if="parseFloat(detail.vipPrice)">
						<view class="text-[32rpx]">会员优惠</view>
						<view class="price-font font-500 text-[32rpx]">
							￥{{ parseFloat(diyGoods.fen2yuan(detail.vipPrice)).toFixed(2) }}
						</view>
					</view>
					<view class=" card-template-item justify-between" v-if="parseFloat(detail.discountPrice)">
						<view class="text-[32rpx]">活动优惠</view>
						<view class="price-font font-500 text-[32rpx]">
							￥{{ parseFloat(diyGoods.fen2yuan(detail.discountPrice)).toFixed(2) }}
						</view>
					</view>

					<view class=" card-template-item justify-between items-baseline">
						<view class="text-[32rpx]">{{ t('orderMoney') }}</view>
						<view class="text-[var(--price-text-color)] price-font">
							<text v-if="parseFloat(detail.usePoint) > 0" class="text-[32rpx]">{{ detail.usePoint }}积分</text>
							<text v-if="parseFloat(detail.usePoint) > 0 && parseFloat(detail.payPrice)"
								class="mx-[4rpx] text-[32rpx]">+</text>
							<text v-if="parseFloat(detail.payPrice) || !parseFloat(detail.usePoint)" class="text-[32rpx]">￥{{
								parseFloat(diyGoods.fen2yuan(detail.payPrice)).toFixed(2) }} </text>
						</view>
					</view>
				</view>

				<view
					class="flex z-2 justify-between items-center bg-[#fff] fixed left-0 right-0 bottom-0 min-h-[120rpx] pl-[36rpx] pr-[20rpx] flex-wrap  pb-ios">
					<view class="flex">
						<view class="flex  mr-[34rpx] flex-col justify-center items-center" @click="orderBtnFn('index')">
							<view class="nc-iconfont nc-icon-shouyeV6xx11 text-[40rpx]"></view>
							<text class="text-[24rpx] mt-[10rpx]">{{ t('index') }}</text>
						</view>
					</view>
					<view class="flex justify-end">
						<view
							class="min-w-[180rpx]  box-border text-[32rpx] h-[70rpx] flex-center border-[2rpx] border-solid border-[#999] rounded-full ml-[20rpx] text-[var(--text-color-light6)]"
							@click="orderBtnFn('logistics')" v-if="showLogistics(detail)">
							{{ t('logisticsTracking') }}
						</view>
						<!-- <view
							class="min-w-[180rpx] box-border text-[28rpx]  h-[70rpx] flex-center text-center border-[2rpx] border-solid border-[#999] rounded-full ml-[20rpx] text-[var(--text-color-light6)]"
							v-if="detail.status == 0" @click="orderBtnFn('close')">{{ t('orderClose') }}</view> -->
						<view
							class="min-w-[180rpx] box-border  text-[32rpx] h-[70rpx] flex-center text-center text-[#fff] primary-btn-bg rounded-full ml-[20rpx]"
							v-if="detail.status == 0" @click="orderBtnFn('pay')">{{ t('topay') }}</view>
						<!-- <view v-if="detail.status == 20"
							class="min-w-[180rpx] box-border  text-[28rpx] h-[70rpx] flex-center text-center  text-[#fff]  primary-btn-bg rounded-full ml-[20rpx]"
							@click="orderBtnFn('finish')">{{ t('orderFinish') }}</view> -->
						<!-- <block v-if="detail.status == 30 && isShowEvaluate">
							<view v-if="!detail.commentStatus"
								class="min-w-[180rpx] box-border text-[28rpx]  h-[70rpx] flex-center border-[2rpx] border-solid border-[#999] rounded-full ml-[20rpx] !text-[var(--text-color-light6)]"
								@click="orderBtnFn('evaluate')">
								{{ detail.isShowEvaluate ? t('selectedEvaluate') : t('evaluate') }}
							</view>
						</block> -->
					</view>
				</view>
			</view>
			<view class="tab-bar-placeholder"></view>
			<pay ref="payRef"></pay>
			<logistics-tracking ref="materialRef"></logistics-tracking>
			<!-- 满减 -->
			<ns-goods-manjian ref="manjianShowRef"></ns-goods-manjian>
		</view>

		<loading-page :loading="loading"></loading-page>

		<!-- #ifdef MP-WEIXIN -->
		<!-- 小程序隐私协议 -->
		<wx-privacy-popup ref="wxPrivacyPopupRef"></wx-privacy-popup>
		<!-- #endif -->
		<!--  海报画板：默认隐藏只用来生成海报。生成方式为主动调用  -->
		<l-painter v-if="showPainter" isCanvasToTempFilePath pathType="url" @success="setPainterImageUrl" hidden
			ref="painterRef" />
	</view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import { t } from '@/locale'
import { img, redirect, copy, goback } from '@/utils/common';
import { getShopOrderDetail, orderClose, orderFinish, getStoreDetail } from '@/addon/shop/api/order';
import { getEvaluateConfig } from '@/addon/shop/api/shop';
import { getVerifyCode } from '@/app/api/verify';
import logisticsTracking from '@/addon/shop/pages/order/components/logistics-tracking/logistics-tracking.vue'
import useConfigStore from "@/stores/config";
import nsGoodsManjian from '@/addon/shop/components/ns-goods-manjian/ns-goods-manjian.vue';
import { topTabar } from '@/utils/topTabbar';
import { cloneDeep } from 'lodash-es';
import { formatOrderStatus, skuSpecFormat, timeFormat, formatOrderType, fen2yuan } from "@/utils/formatting"

import { useGoods } from '@/addon/shop/hooks/useGoods'
const diyGoods = useGoods();
/********* 自定义头部 - start ***********/
const topTabarObj = topTabar()
let topTabbarData = topTabarObj.setTopTabbarParam({ title: '订单详情' })
/********* 自定义头部 - end ***********/
/***渲染二维码 **/
const painterRef = ref(); // 海报画板
const painterImageUrl = ref(); // 海报 url
const showPainter = ref(true)
// 渲染海报
const renderPoster = async (poster) => {
	await painterRef.value.render(poster);
};
// 获得生成的图片
const setPainterImageUrl = (path) => {
	painterImageUrl.value = path;
	showPainter.value = false
};
/**
 * 生成核销二维码
 */
const markCode = (text) => {
	renderPoster({
		css: {
			width: `300px`,
			height: `300px`
		},
		views: [
			{
				type: 'qrcode',
				text: text,
				css: {
					width: `300px`,
					height: `300px`
				}
			}
		]
	})
}
const detail: any = ref<Object>({});
const loading = ref<boolean>(true);
const type = ref('')
const orderId = ref('')
const orderStepsShow = ref(false)
const evaluateConfig = ref<Object>({});
const isShowEvaluate = ref(true)
const manjianShowRef: any = ref(null); //满减送

const sendMessageTitle = ref('')
const sendMessagePath = ref('')
const sendMessageImg = ref('')

const wxPrivacyPopupRef: any = ref(null)

onLoad((option: any) => {
	if (option.order_id) {
		orderId.value = option.order_id;
		orderDetailFn(orderId.value);
		// #ifdef MP
		nextTick(() => {
			if (wxPrivacyPopupRef.value) wxPrivacyPopupRef.value.proactive();
		})
		// #endif
	} else {
		let parameter = {
			url: '/addon/shop/pages/order/list',
			title: '缺少订单id'
		};
		goback(parameter)
	}
});

getEvaluateConfig().then(({ data }) => {
	evaluateConfig.value = data
})

const orderDetailFn = (id: any) => {
	loading.value = true;
	getShopOrderDetail({ id }).then(async (res: any) => {
		detail.value = res.data;
		if (res.data.items && res.data.items.length && isShowVerify.value) {
			let obj: any = {};
			obj.order_goods_id = res.data.items[0].order_goods_id
			// getVerifyCodeFn(obj);
		}

		detail.value.goods = []; //购买商品
		detail.value.gift_goods = []; //赠品
		detail.value.items.forEach((item, index) => {
			if (item.is_gift) {
				detail.value.gift_goods.push(item);
			} else {
				detail.value.goods.push(item);
			}
		})

		// 配送方式：门店自提
		if (res.data.pickUpStoreId) {
			const { data } = await getStoreDetail({ id: res.data.pickUpStoreId });
			detail.value.store = data || {};

		}
		if (detail.value.pickUpVerifyCode) {
			markCode(detail.value.pickUpVerifyCode)
		}
		// let evaluateCount = 0;
		// for (let i = 0; i < detail.value.items.length; i++) {
		// 	if (detail.value.items[i].status != 1 || detail.value.items[i].is_enable_refund == 1) {
		// 		evaluateCount++;
		// 	}
		// }

		// if (evaluateCount == detail.value.items.length) {
		// 	isShowEvaluate.value = false;
		// }

		sendMessageTitle.value = detail.value.items[0].titleName || detail.value.items[0].spuName
		sendMessageImg.value = img(detail.value.items[0].picUrl || '')
		loading.value = false;
	}).catch(() => {
		loading.value = false;
	})
}

// 满减
const manjianOpenFn = (data: any) => {
	let obj = {};
	obj.condition_type = cloneDeep(data).condition_type;
	obj.rule_json = [cloneDeep(data).rule];
	obj.name = cloneDeep(data).manjian_name;
	manjianShowRef.value.open(obj);
}

//关闭订单
const close = (item: any) => {
	uni.showModal({
		title: '提示',
		content: '您确定要关闭该订单吗？',
		confirmColor: useConfigStore().themeColor['--primary-color'],
		success: res => {
			if (res.confirm) {
				orderClose(item.id).then((data) => {
					orderDetailFn(item.id);
				})
			}
		}
	})
}

//订单完成
const finish = (item: any) => {
	// 如果不在微信小程序中
	// #ifndef MP-WEIXIN
	uni.showModal({
		title: '提示',
		content: '您确定物品已收到吗？',
		confirmColor: useConfigStore().themeColor['--primary-color'],
		success: res => {
			if (res.confirm) {
				orderFinish(item.id).then((data) => {
					orderDetailFn(item.id);
				})
			}
		}
	})
	// #endif

	// #ifdef MP-WEIXIN
	// 检测微信小程序是否已开通发货信息管理服务
	if (item.pay && item.pay.type == 'wechatpay' && item.is_trade_managed && wx.openBusinessView) {
		wx.openBusinessView({
			businessType: 'weappOrderConfirm',
			extraData: {
				merchant_id: item.mch_id,
				merchant_trade_no: item.out_trade_no
			},
			success: (res: any) => {
				orderFinish(item.id).then((data) => {
					orderDetailFn(item.id);
				})
			},
			fail: (res: any) => {
				console.log('小程序确认收货组件打开失败 fail', res);
			}
		})
	} else {
		uni.showModal({
			title: '提示',
			content: '您确定物品已收到吗？',
			confirmColor: useConfigStore().themeColor['--primary-color'],
			success: res => {
				if (res.confirm) {
					orderFinish(item.id).then((data) => {
						orderDetailFn(item.id);
					})
				}
			}
		})
	}
	// #endif
}

const goodsEvent = (id: number) => {
	// if (detail.value.activity_type == 'exchange') {
	// 	redirect({
	// 		url: '/addon/shop/pages/point/detail',
	// 		param: {
	// 			id: detail.value.relate_id
	// 		}
	// 	})
	// } else {
	// 	redirect({
	// 		url: '/addon/shop/pages/goods/detail',
	// 		param: {
	// 			goods_id: id
	// 		}
	// 	})
	// }
}

const payRef = ref(null)
const materialRef: any = ref(null)
const orderBtnFn = (type = '') => {
	if (type == 'pay')
		payRef.value?.open('shop', detail.value.payOrderId, `/addon/shop/pages/order/detail?order_id=${detail.value.id}`);
	else if (type == 'close') {
		close(detail.value);
	} else if (type == 'finish') {
		finish(detail.value);
	} else if (type == 'index') {
		redirect({
			url: '/addon/shop/pages/index',
			mode: 'reLaunch'
		});
	} else if (type == 'groupon') {
		redirect({ url: '/addon/shop/pages/groupon/detail', param: { activity_id: detail.value.combinationRecordId }, mode: 'navigateTo' })
	} else if (type == 'sgroupon') {
		let aid = detail.value.combinationActivityId + '-' + detail.value.combinationRecordId
		redirect({ url: '/addon/shop/pages/superGroupon/groupon', param: { aid: aid }, mode: 'navigateTo' })

		// redirect({ url: '/addon/shop/pages/superGroupon/groupon', param: { aid: detail.value.combinationActivityId, hid: detail.value.combinationRecordId }, mode: 'navigateTo' })
	} else if (type == 'logistics') {
		if (detail.value.order_delivery.length > 0) {
			let params = {
				id: detail.value.order_delivery[0].id,
				mobile: detail.value.taker_mobile
			}
			let list: any = []
			detail.value.order_delivery.forEach((item: any, index: number) => {
				item.name = `包裹${index + 1}`
				item.mobile = detail.value.taker_mobile
				list.push(item)
			})

			materialRef.value.open(params);
			materialRef.value.packageList = list
		}
	} else if (type == 'evaluate') {
		if (!detail.value.commentStatus) {
			redirect({ url: '/addon/shop/pages/evaluate/order_evaluate', param: { order_id: detail.value.id } })
		} else {
			redirect({ url: '/addon/shop/pages/evaluate/order_evaluate_view', param: { order_id: detail.value.id } })
		}
	}
}
const dateFormat = (res: any, type: any) => {
	let data;
	if (res.indexOf('/') != -1) {
		data = res.split("/");
	} else if (res.indexOf('-') != -1) {
		data = res.split("-");
	}

	let time;
	const index = new Date(res).getDay();
	const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
	if (type == "yearMonthDay") {
		time = data[0] + '年' + data[1] + '月' + data[2] + '日';
	} else if (type == "yearMonthDayWeek") {
		time = data[0] + '年' + data[1] + '月' + data[2] + '日 ' + week[index];
	} else if (type == "monthDayWeek") {
		time = data[1] + '月' + data[2] + '日 ' + week[index];
	} else {
		time = data[1] + '月' + data[2] + '日';
	}

	return time;
}

const applyRefund = (orderGoodsId: number) => {
	redirect({
		url: '/addon/shop/pages/refund/apply',
		param: {
			order_id: detail.value.id,
			order_goods_id: orderGoodsId
		}
	})
}

const getAddress = () => {
	uni.openLocation({
		latitude: Number(detail.value.taker_latitude),
		longitude: Number(detail.value.taker_longitude),
		success: function () { }
	});
}

const showLogistics = (data: any) => {
	let status = false
	if (data.delivery_type != 'express') return false;
	for (let i = 0; i < data.order_delivery.length; i++) {
		let item = data.order_delivery[i];
		if (item.sub_delivery_type === 'express' && data.status === '3') {
			status = true;
			break;
		} else if (item.sub_delivery_type === 'express' && data.status === '5') {
			status = true;
			break;
		} else {
			status = false
		}
	}
	return status
}

/************ 虚拟商品核销-start ***************/
const verifyGoodsData = ref({}) //虚拟商品
const isShowVerify = computed(() => {
	let bool = false;
	bool = detail.value.deliveryType === 2 && detail.value.payStatus
	// if (detail.value.items.length == 1) {
	// 	verifyGoodsData.value = detail.value.items[0]

	// 	let data = detail.value.items[0];
	// 	bool = data.is_verify == 1 && data.goods_type == 'virtual' && data.delivery_status == 'delivery_finish' && detail.value.status == 3 ? true : false;
	// }
	return bool
})
const verifyInfo = ref([])
// const getVerifyCodeFn = (data: any) => {
// 	verifyInfo.value = [];

// 	getVerifyCode('shopVirtualGoods', data).then((res: any) => {
// 		verifyInfo.value = res.data;
// 	})
// }

/************ 虚拟商品核销-end ***************/
</script>
<style lang="scss" scoped>
.text-item {
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.order-goods-item:nth-child(1) {
	margin-top: 0rpx;
}

.text-color {
	color: $u-primary;
}

.bg-color {
	background-color: $u-primary;
}

.bg-linear {
	background: linear-gradient(94deg, #F84949 8%, #FF9A68 99%);
}

.triangle {
	@apply relative;

	&::before {
		content: "";
		@apply absolute;
		width: 0;
		height: 0;
		position: absolute;
		bottom: -40rpx;
		border: 20rpx solid #EEF3FF;
		border-left-color: transparent;
		border-right-color: transparent;
		border-bottom-color: transparent;
	}
}

.tab-bar-placeholder {
	padding-bottom: calc(constant(safe-area-inset-bottom) + 100rpx);
	padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
}

:deep(.u-image__error) {
	background-color: transparent !important;
}
</style>
